<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="name" label="用户名称">
          <el-input v-model="queryParams.name" placeholder="用户名称" clearable @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item prop="loginName" label="登录名">
          <el-input v-model="queryParams.loginName" placeholder="登录名" clearable @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item prop="nickName" label="微信昵称">
          <el-input v-model="queryParams.nickName" placeholder="微信昵称" clearable @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="queryParams.phone" placeholder="手机号" clearable @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item prop="wxMiniAppType" label="所属小程序">
          <el-select v-model="queryParams.wxMiniAppType">
            <el-option label="菌佑报告小程序" value="REPORT"></el-option>
            <el-option label="菌佑管家小程序" value="MANAGE"></el-option>
            <el-option label="菌佑助手小程序" value="ASSISTANT"></el-option>
            <el-option label="善菌缮君小程序" value="FMT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名称" prop="name"/>
        <el-table-column label="登录名" prop="loginName"/>
        <!-- <el-table-column label="性别" prop="genderText"/> -->
        <el-table-column label="用户来源" prop="sourceText"/>
        <el-table-column label="手机号" prop="phoneNumber"/>
        <el-table-column label="微信昵称" prop="nickName"/>
        <el-table-column label="来源小程序" prop="wxMiniAppTypeText"/>
        <el-table-column label="创建时间" prop="createTimeText"/>
        <el-table-column fixed="right" label="操作"  min-width="280" width="280">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openRoleDialog(scope.row)"
            ><i class="el-icon-set-up"></i> 分配角色</el-button>
            <el-button
              type="warning"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            ><i class="el-icon-edit"></i> 编辑</el-button>
            <el-button
              type="danger"
              size="small"
              :disabled="scope.row.source == 'BUILT_IN'"
              link
              @click="handleDelete(scope.row.id)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 用户表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="500px"
      :before-close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户名称" />
        </el-form-item>

        <el-form-item label="用户登录名" prop="loginName">
          <el-input v-model="formData.loginName" placeholder="请输入登录名" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="formData.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="所属租户" prop="tenantId">
          <el-select v-model="formData.tenantId" placeholder="所属租户">
            <el-option v-for="item in tenantList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色弹窗  -->
    <el-dialog
      :visible.sync="roleDialogVisible"
      :title="'【' + checkedUser.name + '】角色分配'"
      width="800px"
    >
      <el-scrollbar v-loading="loading" max-height="600px">
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="roleList"
          highlight-current-row
          border
          @selection-change="handleSelectionRoleChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="角色名称" prop="zhCnName"/>
          <el-table-column label="角色标识" prop="enName"/>
        </el-table>
      </el-scrollbar>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="allocateRoles">确 定</el-button>
          <el-button @click="closeRoleDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import { formatDate } from '@/utils/formatTime'
import userApi from '@/api/system/user'
import roleApi from '@/api/system/role'
import tenantApi from '@/api/system/tenant'
export default {
	name: 'userIndex',
	data() {
		return {
			queryParams: {
        name: '',
        loginName: '',
        nickName: '',
        phone: '',
        wxMiniAppType: null,
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      roleDialogVisible: false,
      roleList: [],
      checkedUser: {},
      dialog: {},
      formData: {},
      rules: {},

      sourceMap: {
        BUILT_IN: '系统内置',
        SYS_ADD: '系统添加',
        WX_LOGIN: '微信登录',
        PHONE_LOGIN: '手机号登录'
      },
      selectRoleIdArr: [],
      wxMiniAppTypeMap: {
        'FMT': '善菌缮君小程序',
        'REPORT': '菌佑报告小程序',
        'REPORT_WP': '菌佑报告公众号',
        'MANAGE': '菌佑管家小程序',
        'ASSISTANT': '菌佑助手小程序'
      },

      tenantList: [],

		};
	},
  methods: {
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        criteriaVos: [{
          name: 'name',
          searchType: 'LIKE',
          searchVal: this.queryParams.name
        },{
          name: 'loginName',
          searchType: 'LIKE',
          searchVal: this.queryParams.loginName
        },{
          name: 'nickName',
          searchType: 'LIKE',
          searchVal: this.queryParams.nickName
        },{
          name: 'phoneNumber',
          searchType: 'LIKE',
          searchVal: this.queryParams.phone
        },{
          name: 'wxMiniAppType',
          searchType: 'EQUAL',
          searchVal: this.queryParams.wxMiniAppType
        }]
      };
      userApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        data.content.forEach(v => {
          v.genderText = (v.gender != null ? (v.gender == 0 ? '女' : '男') : '-')
          v.sourceText = that.sourceMap[v.source]
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.wxMiniAppTypeText = this.wxMiniAppTypeMap[v.wxMiniAppType];
        });
        this.dataList = data.content;
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        name: '',
        loginName: '',
        nickName: '',
        phone: '',
        wxMiniAppType: null,
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        userApi.update(this.formData).then((res) => {
          this.$message({message: '用户更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        userApi.add(this.formData).then((res) => {
          this.$message({message: '用户添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },

    openRoleDialog(row) {
      this.roleDialogVisible = true;
      this.checkedUser = row;
      
      roleApi.list().then((res) => {
        this.roleList = res.data;
        let that = this;
        this.$nextTick(function () {
					this.roleList.forEach((role) => {
						let users = role.users;
						let userIdArr = [];
						if (users.length > 0) {
							users.forEach((u) => {
								userIdArr.push(u.id);
							});
							if (userIdArr.indexOf(row.id) != -1) {
								that.$refs.multipleTable.toggleRowSelection(role, true);
							}
						}
				})})

      });
    },
    closeRoleDialog() {
      this.roleDialogVisible = false;
      this.roleList = [];
    },

    openDialog(id) {
      tenantApi.list().then(tRes => {
        this.tenantList = tRes.data;
        this.$set(this.dialog, 'visible', true);
        let that = this;
        if (id) {
          this.$set(this.dialog, 'title', '编辑用户');
          userApi.get(id).then((res) => {
            let data = res.data;
            that.formData = data;

          });
        } else {
          this.$set(this.dialog, 'title', '新增用户');
          that.formData = {};
        }
      })
      

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        userApi.delete(id).then((res) => {
          this.$message({message: '用户删除成功！', type: 'success'});
          this.handleQuery();
        });
      } else {
        this.$message.error('暂不支持批量删除用户！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
    allocateRoles() {
      let userId = this.checkedUser.id;
      let roleIdArr = this.selectRoleIdArr;
      userApi.allocateRoles(userId, roleIdArr).then((res) => {
        this.$message({message: '用户角色设置成功！', type: 'success'});
        this.closeRoleDialog();
      });
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>